from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import mixins, viewsets
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle

from .filters import GoodsFilter
from .serializers import GoodsSerializer, CategorySerializer, HotSearchSerializer
from .serializers import BannerSerializer, IndexGoodsSerializer
from .models import Goods, GoodsCategory, HotSearchWords, Banner

# Create your views here.


class GoodsPagination(PageNumberPagination):
    page_size = 12
    page_size_query_param = 'page_size'
    page_query_param = 'page'
    max_page_size = 10


class GoodsViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    list: 商品列表数据
    retrieve: 商品详情
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    throttle_classes = (AnonRateThrottle, UserRateThrottle)
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
    filter_class = GoodsFilter
    ordering_fields = ('sold_num', 'shop_price',)
    search_fields = ('name', 'goods_brief', 'goods_desc')

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_num += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class CategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    list: 商品分类列表数据
    """
    queryset = GoodsCategory.objects.filter(category_type=1)
    serializer_class = CategorySerializer


class HotSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    list: 获取热门搜索词
    """
    queryset = HotSearchWords.objects.all().order_by('-index')
    serializer_class = HotSearchSerializer


class BannerViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    list: 获取轮播图
    """
    queryset = Banner.objects.all()
    serializer_class = BannerSerializer


class IndexGoodsViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    list: 首页商品
    """
    queryset = GoodsCategory.objects.filter(is_tab=True)[0:4]
    serializer_class = IndexGoodsSerializer
